/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package studio.raptor.ddal.core.merger;

import java.util.List;
import studio.raptor.ddal.core.executor.resultset.ResultData;
import studio.raptor.ddal.core.merger.memory.coupling.DistinctCouplingResultData;
import studio.raptor.ddal.core.merger.memory.coupling.GroupByCouplingResultData;
import studio.raptor.ddal.core.merger.memory.coupling.LimitCouplingResultData;
import studio.raptor.ddal.core.merger.memory.coupling.OrderByCouplingResultData;
import studio.raptor.ddal.core.parser.result.ParseResult;
import studio.raptor.ddal.core.parser.result.SQLStatementType;

/**
 * 分片结果集归并工厂
 * @author jackcao
 * @since 3.0.0
 */
public final class MergerFactory {

    private MergerFactory() {}

    public static final ResultData create(SQLStatementType type, List<ResultData> resultDatas, ParseResult parseResult) {
        switch (type) {
            case SELECT:
                return buildDQLResult(resultDatas,parseResult);
            case INSERT:
            case UPDATE:
            case DELETE:
                 return buildIUDResult(resultDatas);
            default:
                return null;
        }
    }

    /**
     * merge select
     *
     * @param resultDatas
     * @param parseResult
     */
    private static ResultData buildDQLResult(List<ResultData> resultDatas,  ParseResult parseResult) {
        //取第一个结果作为返回值
        ResultData result = resultDatas.get(0);
        //构造merge上下文，包含解析上下文及执行返回结果集
        ResultDataMergeContext resultSetMergeContext = new ResultDataMergeContext(resultDatas, parseResult);
        buildCoupling(resultSetMergeContext, buildReducer(resultSetMergeContext,result));
        return result;
    }

    /**
     * merge update，select，delete
     * @param resultDatas
     * @return
     */
    private static ResultData  buildIUDResult(List<ResultData> resultDatas) {
        ResultData result = resultDatas.get(0);
        for(int i = 1,size = resultDatas.size();i < size; i++) {
            result.addAffectedRows(resultDatas.get(i).getAffectedRows());
        }
        return result;
    }

    /**
     * 聚合
     *
     * 将所有分片返回结果放入一个ResultData中
     *
     * @param resultSetMergeContext
     * @param result
     * @return
     */
    private static ResultData buildReducer(ResultDataMergeContext resultSetMergeContext, ResultData result) {
        List<ResultData> resultDatas = resultSetMergeContext.getResultDatas();
        for(int i = 1,size=resultDatas.size(); i<size; i++ ) {
            result.addRows(resultDatas.get(i).getRows());
        }
        return result;
    }

    private static ResultData buildCoupling(ResultDataMergeContext resultSetMergeContext, ResultData resultData) {
        ResultData result =  resultData;
        if (resultSetMergeContext.getParseResult().hasGroupByOrAggregation()) {
            result = new GroupByCouplingResultData(result, resultSetMergeContext).couple();
        }
        if (resultSetMergeContext.getParseResult().hasDistinct()){
            result = new DistinctCouplingResultData(result).couple();
        }
        if (resultSetMergeContext.isNeedMemorySortForOrderBy()) {
            result = new OrderByCouplingResultData(result, resultSetMergeContext).couple();
        }
        if (resultSetMergeContext.getParseResult().hasLimit()) {
            result = new LimitCouplingResultData(result, resultSetMergeContext.getParseResult()).couple();
        }
        return result;
    }
}
